package com.efounder.mobilecomps.contacts;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;

/**
 * @author : zzj
 * @e-mail : zhangzhijun@pansoft.com
 * @date : 2018/12/11 16:31
 * @desc : 汉字转换方法 （全拼或者简拼）
 * @version: 1.0
 */
public class ChineseCharacterUtils {

    /**
     * 获取汉字转换的全拼
     *
     * @param character
     * @return
     */
    public static String getQuanPin(String character) {
        if (character == null) {
            return "";
        }
        String pinyinStr = "";
        char[] newChar = character.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i++) {
            if (newChar[i] > 128) {
                try {
                    if ('、' == newChar[i]) {
                        continue;
                    }
                    pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
                } catch (Exception e) {
                    return pinyinStr;
                }
            } else {
                pinyinStr += newChar[i];
            }
        }
        return pinyinStr;
    }

    /**
     * 获取汉字转换的简拼
     *
     * @param character
     * @return
     */
    public static String getJianPin(String character) {
        if (character == null) {
            return "";
        }
        String pinyinStr = "";
        //转为单个字符
        char[] newChar = character.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i++) {
            if (newChar[i] > 128) {
                try {
                    if ('、' == newChar[i]) {
                        continue;
                    }
                    pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0].charAt(0);
                } catch (Exception e) {
                    return pinyinStr;
                }
            } else {
                pinyinStr += newChar[i];
            }
        }
        return pinyinStr;
    }


    public static void main(String[] args) {
        System.out.println(getJianPin("").toUpperCase()); //转为首字母大写
        System.out.println(getQuanPin("测试测试"));
    }
}
